﻿using MaterialDesignThemes.Wpf;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace MoListv1
{
    /// <summary>
    /// MoListWindow.xaml 的交互逻辑
    /// </summary>
    internal partial class MoListWindow : Window
    {
        public MoListMain PluginMain { get; set; }
        public ObservableCollection<BlackListItem> BlackList { get; set; }
        public ObservableCollection<UserListItem> UserList { get; set; }
        public UniversalCommand AddUserCommand { get; set; }
        public UniversalCommand RemoveUserCommand { get; set; }
        public UniversalCommand RemoveAndBlacklistCommand { get; set; }
        public UniversalCommand ClearUserlistCommand { get; set; }
        public UniversalCommand RemoveBlacklistCommmand { get; set; }
        public UniversalCommand ClearBlacklistCommand { get; set; }
        public DanmuHandler DanmuHandler { get; set; }
        public bool IsLogRedirectDanmaku { get; set; }
        public int LogDanmakuLengthLimit { get; set; }

        public void Log(string text)
        {
            PluginMain.Log(text);

            if (IsLogRedirectDanmaku)
            {
                Task.Run(() =>
                {
                    try
                    {
                        if (!PluginMain.RoomId.HasValue) { return; }

                        string finalText = text.Substring(0, Math.Min(text.Length, LogDanmakuLengthLimit));
                        string result = LoginCenterAPIWarpper.Send(PluginMain.RoomId.Value, finalText);
                        if (result == null)
                        {
                            PluginMain.Log("发送弹幕时网络错误");
                        }
                        else
                        {
                            var j = JObject.Parse(result);
                            if (j["msg"].ToString() != string.Empty)
                            {
                                PluginMain.Log("发送弹幕时服务器返回：" + j["msg"].ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetType().FullName.Equals("LoginCenter.API.PluginNotAuthorizedException"))
                        {
                            IsLogRedirectDanmaku = false;
                        }
                        else
                        {
                            PluginMain.Log("弹幕发送错误 " + ex.ToString());
                        }
                    }
                });
            }
        }

        public MoListWindow(MoListMain moListMain)
        {
            void addResource(string uri)
            {
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
                {
                    Source = new Uri(uri)
                });
            }
            addResource("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml");
            addResource("pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Red.xaml");
            addResource("pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.DeepOrange.xaml");
            addResource("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.ProgressBar.xaml");

            DataContext = this;
            PluginMain = moListMain;

            UserList = new ObservableCollection<UserListItem>();
            BlackList = new ObservableCollection<BlackListItem>();

            DanmuHandler = new DanmuHandler(UserList, BlackList);
            DanmuHandler.LogEvent += (sender, e) => { Log("" + e.Message + (e.Exception == null ? string.Empty : e.Exception.Message)); };

            AddUserCommand = new UniversalCommand((userobj) =>
            {
                if (userobj != null && userobj is string username)
                {
                    UserList.Add(new UserListItem(UserListType.Name, username));
                }
            });

            RemoveUserCommand = new UniversalCommand((listobj) =>
            {
                if (listobj != null && listobj is UserListItem item)
                {
                    UserList.Remove(item);
                }
            });

            RemoveAndBlacklistCommand = new UniversalCommand((userobj) =>
            {
                if (userobj != null && userobj is UserListItem item)
                {
                    BlackList.Add(new BlackListItem((BlackListType)item.UserType, item.Content));
                    UserList.Remove(item);
                }
            });

            ClearUserlistCommand = new UniversalCommand((e) =>
            {
                UserList.Clear();
            });

            RemoveBlacklistCommmand = new UniversalCommand((blackobj) =>
            {
                if (blackobj != null && blackobj is BlackListItem blackListItem)
                {
                    BlackList.Remove(blackListItem);
                }
            });

            ClearBlacklistCommand = new UniversalCommand((x) =>
            {
                BlackList.Clear();
            });

            InitializeComponent();

            ApplyConfig(Config.Load());

            PluginMain.ReceivedDanmaku += (sender, e) => { DanmuHandler.ProcessDanmu(e.Danmaku); };
        }

        private void ApplyConfig(Config config)
        {
            DanmuHandler.MaxTotalItemNum = config.MaxTotalItemNum;
            DanmuHandler.MaxTotalPersonNum = config.MaxTotalPersonNum;
            IsLogRedirectDanmaku = config.IsLogRedirectDanmaku;
            LogDanmakuLengthLimit = config.LogDanmakuLengthLimit;
            UserList.Clear();
            foreach (UserListItem item in config.UserList)
            {
                UserList.Add(item);
            }
            BlackList.Clear();
            foreach (BlackListItem item in config.Blacklist)
            {
                BlackList.Add(item);
            }
        }

        /// <summary>
        /// 收集设置
        /// </summary>
        /// <returns></returns>
        private Config GatherConfig() => new Config()
        {
            MaxTotalItemNum = DanmuHandler.MaxTotalItemNum,
            MaxTotalPersonNum = DanmuHandler.MaxTotalPersonNum,
            UserList = UserList.ToArray(),
            Blacklist = BlackList.ToArray(),
            IsLogRedirectDanmaku = IsLogRedirectDanmaku,
            LogDanmakuLengthLimit = LogDanmakuLengthLimit,
        };

        internal void DeInit()
        {
            Config.Write(GatherConfig());
            try
            {
                Directory.Delete(Utilities.ListCacheDirectoryPath);
            }
            catch (Exception) { };
            //throw new NotImplementedException();
        }
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
            Hide();
        }

        private void DialogAddUserToList(object sender, DialogClosingEventArgs eventArgs)
        {
            if (eventArgs.Parameter.Equals(true) &&
                !string.IsNullOrWhiteSpace(AddUserType.Text) &&
                !string.IsNullOrWhiteSpace(AddUserTextBox.Text))
            {
                string type = AddUserType.Text;
                string keyword = AddUserTextBox.Text;
                if (type == "UID")
                {
                    UserList.Add(new UserListItem(UserListType.Uid, keyword));
                }
                else if (type == "名字")
                {
                    UserList.Add(new UserListItem(UserListType.Name, keyword));
                }
            }
            AddUserType.Text = string.Empty;
            AddUserTextBox.Text = string.Empty;
        }

        private void DialogAddBlackToList(object sender, DialogClosingEventArgs eventArgs)
        {
            if (eventArgs.Parameter.Equals(true) &&
                !string.IsNullOrWhiteSpace(AddBlackType.Text) &&
                !string.IsNullOrWhiteSpace(AddBlackTextBox.Text))
            {
                string type = AddBlackType.Text;
                string keyword = AddBlackTextBox.Text;
                if (type == "UID")
                {
                    BlackList.Add(new BlackListItem(BlackListType.Uid, keyword));
                }
                else if (type == "名字")
                {
                    BlackList.Add(new BlackListItem(BlackListType.Name, keyword));
                }
            }
            AddUserType.Text = string.Empty;
            AddUserTextBox.Text = string.Empty;
        }
    }
}
